package com.quanxiaoha.weblog.common.domain.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.quanxiaoha.weblog.common.domain.dos.EmailVerificationCodeDO;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author: 犬小哈
 * @url: www.quanxiaoha.com
 * @date: 2025-01-28 15:00
 * @description: 邮箱验证码 Mapper
 **/
public interface EmailVerificationCodeMapper extends BaseMapper<EmailVerificationCodeDO> {

    /**
     * 根据邮箱和验证码查询有效的验证码记录
     * @param email 邮箱
     * @param code 验证码
     * @param type 验证码类型
     * @return 验证码记录
     */
    default EmailVerificationCodeDO selectValidCode(String email, String code, Integer type) {
        LambdaQueryWrapper<EmailVerificationCodeDO> wrapper = Wrappers.<EmailVerificationCodeDO>lambdaQuery()
                .eq(Objects.nonNull(email), EmailVerificationCodeDO::getEmail, email)
                .eq(Objects.nonNull(code), EmailVerificationCodeDO::getCode, code)
                .eq(Objects.nonNull(type), EmailVerificationCodeDO::getType, type)
                .eq(EmailVerificationCodeDO::getUsed, false)
                .gt(EmailVerificationCodeDO::getExpireTime, LocalDateTime.now())
                .orderByDesc(EmailVerificationCodeDO::getCreateTime)
                .last("LIMIT 1");
        
        return selectOne(wrapper);
    }

    /**
     * 根据邮箱和类型查询最新的验证码记录
     * @param email 邮箱
     * @param type 验证码类型
     * @return 验证码记录
     */
    default EmailVerificationCodeDO selectLatestByEmailAndType(String email, Integer type) {
        LambdaQueryWrapper<EmailVerificationCodeDO> wrapper = Wrappers.<EmailVerificationCodeDO>lambdaQuery()
                .eq(Objects.nonNull(email), EmailVerificationCodeDO::getEmail, email)
                .eq(Objects.nonNull(type), EmailVerificationCodeDO::getType, type)
                .orderByDesc(EmailVerificationCodeDO::getCreateTime)
                .last("LIMIT 1");
        
        return selectOne(wrapper);
    }

    /**
     * 标记验证码为已使用
     * @param id 验证码ID
     * @return 更新结果
     */
    default int markAsUsed(Long id) {
        EmailVerificationCodeDO updateEntity = EmailVerificationCodeDO.builder()
                .id(id)
                .used(true)
                .build();
        return updateById(updateEntity);
    }

    /**
     * 清理过期的验证码
     * @return 清理数量
     */
    default int cleanExpiredCodes() {
        LambdaQueryWrapper<EmailVerificationCodeDO> wrapper = Wrappers.<EmailVerificationCodeDO>lambdaQuery()
                .lt(EmailVerificationCodeDO::getExpireTime, LocalDateTime.now());
        return delete(wrapper);
    }
}
